package com.alibaba.citrus.ots.unified.inventory.repository.impl;
import com.alibaba.citrus.ots.common.annotation.EpochTransactional;
import com.alibaba.citrus.ots.unified.inventory.repository.AllocateApplyOrderDetailWriteRepository;
import com.alibaba.citrus.ots.unified.inventory.utils.InfoUtil;
import com.epoch.app.otsunifiedinventory.domain.allocateapplyorderdetail.dto.DeleteAllocateApplyOrderDetailRequest;
import com.epoch.app.otsunifiedinventory.domain.allocateapplyorderdetail.model.AllocateApplyOrderDetail;
import com.epoch.app.otsunifiedinventory.domain.allocateapplyorderdetail.service.AllocateApplyOrderDetailService;
import com.epoch.app.otsunifiedinventory.sdo.AllocateApplyOrderDetailSDO;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.RoundingMode;
import java.util.List;
import java.util.Objects;

/**
 * @author heyu
 * @description 调拨单详情写服务
 */
@Component
public class AllocateApplyOrderDetailWriteRepositoryImpl implements AllocateApplyOrderDetailWriteRepository {

    @Resource
    private AllocateApplyOrderDetailService allocateApplyOrderDetailService;

    @Override
    @EpochTransactional(appCode="bc_ots", dataSourceCode = "cr_ots", dataSourceType = "app")
    public void batchCreateAllocateApplyOrderDetail(List<AllocateApplyOrderDetailSDO> allocateApplyOrderDetailSDOList) {
        if (CollectionUtils.isNotEmpty(allocateApplyOrderDetailSDOList)) {
            allocateApplyOrderDetailSDOList.forEach(allocateApplyOrderDetailSDO -> {
                createAllocateApplyOrderDetail(allocateApplyOrderDetailSDO);
            });
        }
    }

    @Override
    public void createAllocateApplyOrderDetail(AllocateApplyOrderDetailSDO allocateApplyOrderDetailSDO) {
        AllocateApplyOrderDetail request = new AllocateApplyOrderDetail();
        BeanUtils.copyProperties(allocateApplyOrderDetailSDO,request);
        request.setGoodsName(allocateApplyOrderDetailSDO.getTitle());
        request.setGoodsCode(allocateApplyOrderDetailSDO.getScItemId());
        request.setGoodsId(InfoUtil.getScItemIdByOutCode(allocateApplyOrderDetailSDO.getScItemId()));
        request.setSendBackRequired(allocateApplyOrderDetailSDO.getReturnGood());
        request.setUnitPrice(Objects.nonNull(request.getUnitPrice())?request.getUnitPrice().setScale(4, RoundingMode.HALF_UP):null);
        request.setSubtotalMoney(Objects.nonNull(request.getSubtotalMoney())?request.getSubtotalMoney().setScale(4, RoundingMode.HALF_UP):null);
        allocateApplyOrderDetailService.create(request);
    }

    @Override
    public void deleteDetailByOrderId(Long id) {
        //删除调拨预报单详情
        DeleteAllocateApplyOrderDetailRequest deleteRequest = new DeleteAllocateApplyOrderDetailRequest();
        deleteRequest.setId(id.intValue());
        allocateApplyOrderDetailService.deleteAllocateApplyOrderDetail(deleteRequest);
    }
}
